import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.bcel.internal.generic.Select;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper mapper=new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        BlogDao blogDao=new BlogDao();
        String blogId=req.getParameter("blogId");
        if(blogId!=null){
            //按照Id查找
            Blog blog=blogDao.selectById(Integer.parseInt(blogId));
            resp.getWriter().write(mapper.writeValueAsString(blog));
        }else {
            List<Blog>list=blogDao.selectAll();
            resp.getWriter().write(mapper.writeValueAsString(list));
        }

    }
//新增blog
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session=req.getSession();
        //未登录 防直接进入
        if (session==null){
            resp.sendRedirect("login.html");
            return;
        }
        User user= (User) session.getAttribute("user");
        if(user==null){
            resp.sendRedirect("login.html");
            return;
        }
        //确定编码后，构建blog
        req.setCharacterEncoding("utf8");
        Blog blog=new Blog();
        blog.setTitle(req.getParameter("title"));
        blog.setContent(req.getParameter("content"));
        blog.setUserId(user.getUserId());
        BlogDao blogDao=new BlogDao();
        blogDao.insert(blog);
        //更新user
        user.setBlogCount(user.getBlogCount()+1);
        session.setAttribute("user",user);
        resp.sendRedirect("blog_list.html");
    }
}
